import datetime
import requests
from common.log import logger

WECHAT_PREFIX_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s"


class WeChatMessage:
    msg_type = None

    def __init__(self, raw_message: dict):
        self.raw_message = raw_message

    def message(self) -> dict:
        """生成企业微信发送的信息

        """
        raise NotImplementedError("message must be implemented")


class WeChatMessageMarkDown(WeChatMessage):
    msg_type = "markdown"

    def message(self) -> dict:
        content = ""
        for key, value in self.raw_message.items():
            content += '> %s:<font color="comment">%s</font> \n' % (key, value)
        content += str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

        return {
            "msgtype": "markdown",
            "markdown": {
                "content": content
            }
        }


class WeChatMessageText(WeChatMessage):
    msg_type = "text"

    def message(self) -> dict:
        content = ""
        for key, value in self.raw_message.items():
            content += "{}:{}\n".format(key, value)

        content += str(datetime.datetime.now())

        return {
            'msgtype': 'text',
            'text': {
                "content": content,
            }
        }


def send_wechat(msg: dict, msgtype: str = "markdown",webhook: str= None):
    """
    msgtype: markdown、text
    """
    try:
        headers = {
            'Content-Type': 'application/json'
        }
        wechat_obj = None
        for wechat in WeChatMessage.__subclasses__():
            if wechat.msg_type == msgtype:
                wechat_obj = wechat
                break

        if not wechat_obj:
            logger.error("send wechat msgtype(%s) not implemented" % msgtype)
            return

        wechat = wechat_obj(msg)
        message = wechat.message()
        logger.info("send wechat data:%s" % message)
        response = requests.request("POST", webhook, headers=headers, json=message, timeout=1,verify=False)
        content = response.text
        logger.info("send wechat result——{}".format(content))
        return content
    except Exception as e:
        logger.exception(e)
        return ''
